package com.springboot.util;

import com.springboot.common.exception.ParameterException;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

/**
 * 日期工具类, 继承org.apache.commons.lang.time.DateUtils类
 *
 * <p>JDK1.8推出了一个时间工具类LocalDateTime，灰常好用，可以尝试替换</p>
 *
 * @author yanhai
 * @version 1.0
 */
public class DateUtils extends org.apache.commons.lang3.time.DateUtils {

    private static String[] parsePatterns = {
            "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
            "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
            "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM","yyyyMMdd"};

    public static final String CLASSIC_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";

    /**
     * 得到当前日期字符串 格式（yyyy-MM-dd）
     */
    public static String getDate() {
        return getDate("yyyy-MM-dd");
    }

    /**
     * 得到当前日期字符串 格式（yyyy-MM-dd） pattern可以为："yyyy-MM-dd" "HH:mm:ss" "E"
     */
    public static String getDate(String pattern) {
        return DateFormatUtils.format(new Date(), pattern);
    }

    /**
     * 得到日期字符串 默认格式（yyyy-MM-dd） pattern可以为："yyyy-MM-dd" "HH:mm:ss" "E"
     */
    public static String formatDate(Date date, Object... pattern) {
        String formatDate = null;
        if (pattern != null && pattern.length > 0) {
            formatDate = DateFormatUtils.format(date, pattern[0].toString());
        } else {
            formatDate = DateFormatUtils.format(date, "yyyy-MM-dd");
        }
        return formatDate;
    }


    /**
     * 得到日期字符串 默认格式（yyyy-MM-dd） pattern可以为："yyyy-MM-dd" "HH:mm:ss" "E"
     */
    public static String formatDate(String dateStr, Object... pattern) {
        Date date = parseDate(dateStr);
        String formatDate = null;
        if (pattern != null && pattern.length > 0) {
            formatDate = DateFormatUtils.format(date, pattern[0].toString());
        } else {
            formatDate = DateFormatUtils.format(date, "yyyy-MM-dd");
        }
        return formatDate;
    }


    /**
     * 得到日期时间字符串，转换格式（yyyy-MM-dd HH:mm:ss）
     */
    public static String formatDateTime(Date date) {
        return formatDate(date, "yyyy-MM-dd HH:mm:ss");
    }

    /**
     * 得到当前时间字符串 格式（HH:mm:ss）
     */
    public static String getTime() {
        return formatDate(new Date(), "HH:mm:ss");
    }

    /**
     * 得到当前日期和时间字符串 格式（yyyy-MM-dd HH:mm:ss）
     */
    public static String getDateTime() {
        return formatDate(new Date(), "yyyy-MM-dd HH:mm:ss");
    }

    /**
     * 得到当前年份字符串 格式（yyyy）
     */
    public static String getYear() {
        return formatDate(new Date(), "yyyy");
    }

    /**
     * 得到当前月份字符串 格式（MM）
     */
    public static String getMonth() {
        return formatDate(new Date(), "MM");
    }

    /**
     * 得到当天字符串 格式（dd）
     */
    public static String getDay() {
        return formatDate(new Date(), "dd");
    }

    /**
     * 得到当前星期字符串 格式（E）星期几
     */
    public static String getWeek() {
        return formatDate(new Date(), "E");
    }

    /**
     * 日期型字符串转化为日期 格式
     * { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm",
     * "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm",
     * "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm" }
     */
    public static Date parseDate(Object str) {
        if (str == null) {
            return null;
        }
        try {
            return parseDate(str.toString(), parsePatterns);
        } catch (ParseException e) {
            return null;
        }
    }

    /**
     * 获取过去的天数
     *
     * @param date
     * @return
     */
    public static long pastDays(Date date) {
        long t = System.currentTimeMillis() - date.getTime();
        return t / (24 * 60 * 60 * 1000);
    }

    /**
     * 获取过去的小时
     *
     * @param date
     * @return
     */
    public static long pastHour(Date date) {
        long t = System.currentTimeMillis() - date.getTime();
        return t / (60 * 60 * 1000);
    }

    /**
     * 获取过去的分钟
     *
     * @param date
     * @return
     */
    public static long pastMinutes(Date date) {
        long t = System.currentTimeMillis() - date.getTime();
        return t / (60 * 1000);
    }

    /**
     * 转换为时间（天,时:分:秒.毫秒）
     *
     * @param timeMillis
     * @return
     */
    public static String formatDateTime(long timeMillis) {
        long day = timeMillis / (24 * 60 * 60 * 1000);
        long hour = (timeMillis / (60 * 60 * 1000) - day * 24);
        long min = ((timeMillis / (60 * 1000)) - day * 24 * 60 - hour * 60);
        long s = (timeMillis / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
        long sss = (timeMillis - day * 24 * 60 * 60 * 1000 - hour * 60 * 60 * 1000 - min * 60 * 1000 - s * 1000);
        return (day > 0 ? day + "," : "") + hour + ":" + min + ":" + s + "." + sss;
    }

    /**
     * 获取两个日期之间的天数
     *
     * @param before
     * @param after
     * @return
     */
    public static double getDistanceOfTwoDate(Date before, Date after) {
        long beforeTime = before.getTime();
        long afterTime = after.getTime();
        return (afterTime - beforeTime) / (1000 * 60 * 60 * 24);
    }

    /**
     * 获取两个日期之间的天数
     *
     * @param before
     * @param after
     * @return
     */
    public static Long getDistanceOfTwoDateForLong(Date before, Date after) {
        long beforeTime = before.getTime();
        long afterTime = after.getTime();
        return (afterTime - beforeTime) / (1000 * 60 * 60 * 24);
    }

    /**
     * 获得指定日期的前几天
     *
     * @param specifiedDay 置顶日期
     * @param days         前几天
     * @return
     * @throws Exception
     */
    public static String getSpecifiedDayBefore(String specifiedDay, Integer days) {
        Calendar c = Calendar.getInstance();
        Date date = null;
        try {
            date = new SimpleDateFormat("yy-MM-dd").parse(specifiedDay);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        c.setTime(date);
        int day = c.get(Calendar.DATE);
        c.set(Calendar.DATE, day - days);

        String dayBefore = new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
        return dayBefore;
    }

    /**
     * 获得指定日期的后几天
     *
     * @param specifiedDay 指定日期
     * @param days         后几天
     * @return
     * @throws Exception
     */
    public static String getSpecifiedDayAfter(String specifiedDay, Integer days) {
        Calendar c = Calendar.getInstance();
        Date date = null;
        try {
            date = new SimpleDateFormat("yy-MM-dd").parse(specifiedDay);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        c.setTime(date);
        int day = c.get(Calendar.DATE);
        c.set(Calendar.DATE, day + days);

        String dayAfter = new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
        return dayAfter;
    }


    /**
     * 获得指定日期的前几月
     *
     * @param specifiedMonth 置顶日期
     * @param months         前几月
     * @return
     * @throws Exception
     */
    public static String getSpecifiedMonthBefore(String specifiedMonth, Integer months) {
        Calendar c = Calendar.getInstance();
        Date date = null;
        try {
            date = parseDate(specifiedMonth,parsePatterns);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        c.setTime(date);
        int month = c.get(Calendar.MONTH);
        c.set(Calendar.MONTH, month - months);

        String monthBefore = new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
        return monthBefore;
    }

    /**
     * 获得指定日期的后几月
     *
     * @param specifiedMonth 置顶日期
     * @param months         后几月
     * @return
     * @throws Exception
     */
    public static String getSpecifiedMonthAfter(String specifiedMonth, Integer months) {
        Calendar c = Calendar.getInstance();
        Date date = null;
        try {
            date = parseDate(specifiedMonth,parsePatterns);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        c.setTime(date);
        int month = c.get(Calendar.MONTH);
        c.set(Calendar.MONTH, month + months);

        String monthAfter = new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
        return monthAfter;
    }

    /**
     * 计算月份差(忽略日期)
     */
    public static int monDifference(Date beginmonth, Date endmonth) {
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMM");
        String beginDate = sdf1.format(beginmonth);
        int q = Integer.parseInt(beginDate);

        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMM");
        String endDate = sdf2.format(endmonth);
        int d = Integer.parseInt(endDate);


        int n = 0;
        int m = 0;
        if (q > d) {
            return -1;
        }
        if (q == d) {
            return 0;
        } else {
            if ((d / 100) == (q / 100)) {
                n = (d % 100) - (q % 100);
            } else {
                n = d % 100;
                m = d / 100;
                while ((m - 1) > (q / 100)) {
                    m--;
                    n = n + 12;
                }
                ;
                n = n + 12 - (q % 100);
            }
        }
        return n;
    }

    /**
     * 判断两个DATE是否在一个月内
     */
    public static boolean comMon(Date d1, Date d2) {
        Calendar css = Calendar.getInstance();
        Calendar cbb = Calendar.getInstance();
        css.setTime(d1);
        cbb.setTime(d2);
        int sy = css.get(Calendar.YEAR);
        int sm = css.get(Calendar.MONTH);
        int ey = cbb.get(Calendar.YEAR);
        int em = cbb.get(Calendar.MONTH);
        return sy == ey && sm == em;
    }

    /**
     * 计算日期差
     *
     * @throws ParseException
     */
    public static long getDiffDay(Date begindate, Date enddate) {

        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
        String beginDate = sdf1.format(begindate);

        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
        String endDate = sdf2.format(enddate);


        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        long checkday = 0l;
        //��ʼ�����������
        try {
            checkday = (formatter.parse(endDate).getTime() - formatter.parse(beginDate).getTime()) / (1000 * 24 * 60 * 60);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return checkday;
    }

    /**
     * 某月的最后一天
     */
    public static int getMonDays(Date d) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(d);
        int MaxDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
        return MaxDay;
    }

    /**
     * 某月第一天
     *
     * @param d Date型-日期
     * @return
     */
    public static String getFirstDayOFMon(Date d) {
        Calendar cd = Calendar.getInstance();
        cd.setTime(d);
        cd.set(Calendar.DAY_OF_MONTH, 1);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(cd.getTime());
    }

    /**
     * 某月第一天
     *
     * @param date String型-日期
     * @return
     */
    public static String getFirstDayOFMon(String date) {
        return getFirstDayOFMon(parseDate(date));
    }

    /**
     * 某月最后一天
     *
     * @param d Date型-日期
     * @return
     */
    public static String getLastDayOFMon(Date d) {
        Calendar cd = Calendar.getInstance();
        cd.setTime(d);
        cd.set(Calendar.DAY_OF_MONTH, cd.getActualMaximum(Calendar.DAY_OF_MONTH));
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(cd.getTime());
    }

    /**
     * 某月最后一天
     *
     * @param date String型-日期
     * @return
     */
    public static String getLastDayOFMon(String date) {
        return getLastDayOFMon(parseDate(date));
    }

    /**
     * 获取两个日期之间的月份数
     *
     * @param beginmonth
     * @param endmonth
     * @return
     */
    public static int monDifferenceWithDay(Date beginmonth, Date endmonth) {
        int n = 0;

        Calendar beginCal = Calendar.getInstance();
        Calendar endCal = Calendar.getInstance();
        beginCal.setTime(beginmonth);
        beginCal.add(Calendar.MONTH, 1);
        endCal.setTime(endmonth);

        while (beginCal.getTime().before(endCal.getTime())) {
            beginCal.add(Calendar.MONTH, 1);
            n++;
        }


        return n;
    }


    /**
     * 获取两个日期之间的月份数
     *
     * @param beginmonth
     * @param endmonth
     * @return
     */
    public static int monDifferenceIncludeDay(Date beginmonth, Date endmonth) {
        int n = 0;

        Calendar beginCal = Calendar.getInstance();
        Calendar endCal = Calendar.getInstance();
        beginCal.setTime(beginmonth);
        beginCal.add(Calendar.MONTH, 1);
        endCal.setTime(endmonth);

        while (!beginCal.getTime().after(endCal.getTime())) {
            beginCal.add(Calendar.MONTH, 1);
            n++;
        }


        return n;
    }

    /**
     * 判断两个日期是否在同一天里
     */
    public static boolean comDay(Date d1, Date d2) {
        Calendar css = Calendar.getInstance();
        Calendar cbb = Calendar.getInstance();
        css.setTime(d1);
        cbb.setTime(d2);
        int sy = css.get(Calendar.YEAR);
        int sm = css.get(Calendar.MONTH);
        int sd = css.get(Calendar.DAY_OF_MONTH);
        int ey = cbb.get(Calendar.YEAR);
        int em = cbb.get(Calendar.MONTH);
        int ed = cbb.get(Calendar.DAY_OF_MONTH);

        return sy == ey && sm == em && sd == ed;
    }

    /**
     * 计算两个日期之间相差的天数。
     *
     * @param lower 时间下限。
     * @param upper 时间上限。
     * @return 相差天数。
     */
    public static int getIntervalByDays(Date lower, Date upper) {
        if (lower == null || upper == null) {
            return 0;
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            lower = sdf.parse(sdf.format(lower));
            upper = sdf.parse(sdf.format(upper));
        } catch (ParseException ex) {
            throw new IllegalStateException(ex);
        }
        Calendar cal = Calendar.getInstance();
        cal.setTime(lower);
        long time1 = cal.getTimeInMillis();
        cal.setTime(upper);
        long time2 = cal.getTimeInMillis();
        long between_days = (time2 - time1) / (1000 * 3600 * 24);
        return Integer.parseInt(String.valueOf(between_days));
    }

    /**
     * 计算两个日期之间相差的天数。
     *
     * @param lower 时间下限。
     * @param upper 时间上限。
     * @return 相差天数。
     */
    public static int getIntervalByDays(Timestamp lower, Timestamp upper) {
        if (lower == null || upper == null) {
            return 0;
        }
        return getIntervalByDays((Date) lower, (Date) upper);
    }

    /**
     * 将字符串日期转换成{@link Date}。
     *
     * @param date 字符串日期。
     * @param format 字符串日期格式。
     * @return {@link Date}。
     */
    public static Date parseString(String date, String format) {
        if (StringUtils.isBlank(date)) {
            return null;
        }
        String formatStr;
        if (format == null) {
            formatStr = CLASSIC_DATE_FORMAT;
        } else {
            formatStr = format;
        }
        SimpleDateFormat sdf = new SimpleDateFormat(formatStr);
        try {
            return sdf.parse(date);
        } catch (ParseException ex) {
            throw new ParameterException(ex);
        }
    }

    /**
     * 将字符串日期转换成{@link Date}。
     *
     * @param date 字符串日期。
     * @return {@link Date}。
     */
    public static Date parseString(String date) {
        if (CommonUtils.isBlank(date)) {
            return null;
        }
        String ydate = "";
        String ytime = "";
        String dType = "yyyy年MM月dd日";
        String tType = "HH:mm:ss";
        if (3 < date.split(" ").length) {
            try {
                return new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.SIMPLIFIED_CHINESE).parse(date);
            } catch (ParseException e) {
                return null;
            }
        }

        if (date.indexOf(" ") > 0) {
            ydate = date.substring(0, date.indexOf(" "));
        } else {
            ydate = date;
        }
        if (10 < date.indexOf(" ") + 1) {
            ytime =
                    date.substring(date.indexOf(" ") + 1, date.length());
        } else {
            ytime = "00:00:00";
        }

        if (ydate.indexOf("-") > 0) {
            dType = "yyyy-MM-dd";
        } else if (ydate.indexOf("年") > 0) {
            if ((ydate.indexOf("年") > 0) && (ydate.indexOf("月") > 0) &&
                    (ydate.indexOf("年") < ydate.indexOf("月"))) {
                dType = "yyyy年MM月dd日";
            } else if ((ydate.indexOf("年") > 0) &&
                    (ydate.indexOf("月") > 0) &&
                    (ydate.indexOf("年") > ydate.indexOf("月"))) {
                dType = "MM月dd日yyyy年";
            }
        } else if ((ydate.indexOf("/") > 0) && (ydate.indexOf("/") == 4)) {
            dType = "yyyy/MM/dd";
        } else if ((ydate.indexOf("/") > 0) &&
                (ydate.indexOf("/") == 2)) {
            dType = "MM/dd/yyyy";
        }

        if (1 < ytime.indexOf("时")) {
            tType = "HH时mm分ss秒";
            if (ytime.length() == 6) {
                ytime = ytime + "00秒 ";
            }
        } else if (1 < ytime.indexOf(":")) {
            tType = "HH:mm:ss";
            if (ytime.length() == 5) {
                ytime = ytime + ":00";
            }
        } else {
            tType = null;
        }
        date = ydate + " " + ytime;
        try {
            return new SimpleDateFormat(dType + " " + tType).parse(date);
        } catch (ParseException ex) {
            throw new IllegalStateException(ex);
        }
    }

}
